import 'dart:convert';

import 'package:dynamic_stock/comm/alert_tool.dart';
import 'package:dynamic_stock/const/const.dart';
import 'package:dynamic_stock/model/login_model.dart';
import 'package:dynamic_stock/network/network.dart';
import 'package:dynamic_stock/root/root_page.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';



class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  TextEditingController _editingController;
  TextEditingController _pwdeditingController;

  bool _isAction = false;
  bool _ispwd = true;

  @override
  void initState() {
    _editingController = TextEditingController();
    _pwdeditingController = TextEditingController();
    super.initState();
  }

  @override
  void dispose() {
    _editingController.dispose();
    _pwdeditingController.dispose();
    super.dispose();
  }

  _textOnChange(String string) {
    setState(() {
      _isAction = _editingController.text != "" && _pwdeditingController.text != "";
    });
  }

  _cacheUserData(UserData userData) async {
    String json = jsonEncode(userData.toJson());
    SharedPreferences share = await SharedPreferences.getInstance();
    share.setString(USER_CACHE_KEY, json);
    share.setString(USER_LOGIN_ID, userData.platUserId);
  }

  

  _login(BuildContext context) async {
    AlertTool.showLoadingDialog(context, "正在登录");
    try {
      LoginModel model = await NetworkTool().request_login(
        {"password":_pwdeditingController.text,"userName":_editingController.text,"platUserLoginType":2}
      );

      if(model.errcode == 0) {
        // 缓存数据
        await _cacheUserData(model.data);
        Navigator.of(context).pop();
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (context) => RootPage()
        ));
      } else {
        _scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text(model.message),
          duration: Duration(milliseconds: 1000),
        ));
        Navigator.of(context).pop();
      }
    } catch (e) {
      print(e.toString());
      Navigator.of(context).pop();
      _scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text(e.toString()),
          duration: Duration(milliseconds: 1000),
        ));
    }
  }

  @override
  Widget build(BuildContext context) {

    Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          alignment: Alignment.center,
          child: Container(
            child: Column(
              children: <Widget>[
                SizedBox(height: screenSize.height * 0.15,),
                Image.asset('assets/appIcon.png'),
                SizedBox(height: 18,),
                Text(
                  "欢迎加入城市合伙人",
                  style: TextStyle(color: Color(0xff35343D), fontSize: 18, fontWeight: FontWeight.w500),
                ),
                SizedBox(height: screenSize.height * 0.1,),
                _createInputText(
                  Icon(Icons.person, color: Color(0xffdad9e1)), 
                  "请输入用户账号", 
                  _editingController,
                  IconButton(icon: Icon(Icons.cancel, color: Color(0xffdddddd), size: 18,),onPressed: (){
                    _editingController.text = "";
                  })
                ),
                SizedBox(height: 20,),
                _createInputText(
                  Image.asset("assets/lock-ico.png"), 
                  "请输入用密码吧", 
                  _pwdeditingController,
                  IconButton(icon: Icon(_ispwd ? Icons.visibility_off : Icons.visibility,color: Color(0xffdddddd), size: 18,), onPressed: (){
                    setState(() {
                      _ispwd = !_ispwd;
                    });
                  })
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 20, left: 30, right: 30),
                          child: RaisedButton(
                            disabledColor: Color(0xff6BE0C6),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(vertical: 13),
                              child: Text("登录",style: TextStyle(color: Colors.white, fontSize: 15)),
                            ),
                            elevation: 3,
                            color: AppMainColor.mainColor,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
                            onPressed: _isAction ? (){
                              _login(context);
                            } : null,
                          ),
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _createInputText(Widget leftIcon, String placeholeder, TextEditingController controller, Widget right) {
    return Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  height: 47,
                  margin: EdgeInsets.only(left: 30, right: 30),
                  child: PhysicalModel(
                    color: Color(0xffFBFAFF),
                    borderRadius: BorderRadius.circular(23.5),
                    child: Row(
                      children: <Widget>[
                        SizedBox(width: 21),
                        leftIcon,
                        Expanded(
                          child: TextField(
                            controller: controller,
                            onChanged: _textOnChange,
                            style: TextStyle(
                              fontSize: 15,
                              color: AppMainColor.tabbarTitleColor
                            ),
                            keyboardType: TextInputType.visiblePassword,
                            obscureText: controller == _pwdeditingController && _ispwd,
                            
                            decoration: InputDecoration(
                              contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 13),
                              hintText: placeholeder,
                              border: InputBorder.none
                            ),
                          ),
                        ),
                        right
                      ],
                    ),
                  ),
                ),
              )
            ],
          );
  }
}